package com.zhanghp.refer;

/**
 * @author zhanghp
 * @since 2023/10/18 17:35
 */
public class ListNode {
    public int val;
    public ListNode next;

    public ListNode(int value) {
        this.val = value;
        next = null;
    }

    /**
     * 随机生成LinkedList
     *
     * @param size     最大长度
     * @param maxValue 节点最大值
     * @return 节点集合
     */
    public static ListNode generateRandomLinkedList(int size, int maxValue) {
        // 1. 随机生成长度
        int length = (int) (Math.random() * (size + 1));
        // 2. 长度为0返回null
        while (length == 0 || length < 5) {
            length = (int) (Math.random() * (size + 1));
        }
        // 3. 先生成一个节点，所以需要size--
        length--;
        // 4. 先生成头节点
        ListNode head = new ListNode(((int) (Math.random() * (maxValue + 1))));
        // 5. 生成中间变量节点
        ListNode pre = head;

        // 6. 下一节点生成
        while (length != 0) {
            ListNode cur = new ListNode(((int) (Math.random() * maxValue)));
            pre.next = cur;
            // 重新赋值
            pre = cur;
            length--;
        }
        return head;
    }

    /**
     * 打印
     *
     * @param node node
     */
    public static void printLinkedList(ListNode node) {
        System.out.print("LinkedList: ");
        while (node != null) {
            if (node.next == null) {
                System.out.print(node.val);
                break;
            }
            System.out.print(node.val + " -> ");
            node = node.next;
        }
        System.out.println();
    }
}
